﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Microsoft.Practices.ServiceLocation;
using AzureGames.Domain.Handlers;
using AzureGames.Domain.Models;

namespace AzureGames.Web.Controllers
{
    public class UserController : AuthorizedController
    {
        public UserController(IServiceLocator serviceLocator) : base(serviceLocator) { }

        [Authorize]
        public ActionResult Profile()
        {
            Model.User user = Session["User"] as Model.User;

            return View(Using<GetGameUser>().Execute(user.ID));
        }

        [Authorize]
        [HttpPost]
        public ActionResult Profile(GameUser user)
        {
            if (ModelState.IsValid)
            {
                Using<UpdateGameUser>().Execute(user);
                return RedirectToRoute("Dashboard");
            }

            return View(user);
        }

        public ActionResult Avatar()
        {
            return View();
        }

        [HttpPost]
        public ActionResult UploadAvatar(HttpPostedFileBase avatarFile)
        {
           if (avatarFile != null && avatarFile.ContentLength > 0)
           {
              
               //it is possible that the functionality in this method should be 
               //encapsulated into the UpdateGameUser handler as a new method on that

               //first it updates the GameUser with a new guid for the new image
               //then it adds the image to the repository using that guid as the id
               Model.User user = Session["User"] as Model.User;
               var gameUser = Using<GetGameUser>().Execute(user.ID);
               //Generate new avatar guid 
               gameUser.AvatarImage = Guid.NewGuid();
               Using<UpdateGameUser>().Execute(gameUser);

               byte[] byteArray = new byte[avatarFile.ContentLength];
               avatarFile.InputStream.Read(byteArray, 0, avatarFile.ContentLength);
               //save the avatar image to the blob storage
               Model.Resource res = new Model.Resource
               {
                   Bytes = byteArray,
                   ContentType = avatarFile.ContentType,
                   ID = gameUser.AvatarImage,
                   Name = string.Format("{0}'s Avatar", user.Name),
                   CreatedDate = DateTime.Now,
                   LastUpdatedDate = DateTime.Now
               };

               Using<UpdateResource>().Execute(res);
           }

            return RedirectToAction("Profile");
        }

        [OutputCache(Duration = int.MaxValue, VaryByParam = "resourceID")]
        public FileContentResult GetResource(Guid resourceID, string contentType)
        {
           return new FileContentResult(Using<AzureGames.Domain.Handlers.GetResource>().Execute(resourceID).Bytes, contentType);
        }
    }
}
